//
//  PerSettingViewController.m
//  sklive
//
//  Created by Macx on 2017/4/26.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PerSettingViewController.h"
#import "LoginViewController.h"
//#import "PerMessageDetailsViewController.h"
#import "BindingPhoneViewController.h"
#import "PlatformIntroViewController.h"
#import "ChangePassWordViewController.h"
#import "FeedbackViewController.h"
#import "BaseNavViewController.h"
#import "APPServer.h"

@interface PerSettingViewController () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITableViewCell *cell;
@property (nonatomic, strong) NSArray *infoArr;

@end

@implementation PerSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    self.infoArr = @[@[@"修改密码"], @[@"清理缓存", @"帮助", @"关于平台"]];
    self.infoArr = @[@[@"手机绑定",@"修改密码"], @[@"清理缓存", @"关于平台", @"联系客服：178-2583-8589", @"反馈与意见"]];
    
    [self buildUI];
}

#pragma mark ==========构建UI==========
- (void)buildUI {

    self.navigationItem.title = @"设置";
    self.view.backgroundColor = UISeparatedColorRGB;
   
//    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, ([LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+40)*4+10) style:UITableViewStylePlain];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, ([LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+20)*6+10) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.scrollEnabled = NO;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    _tableView.estimatedRowHeight = 0;
    _tableView.estimatedSectionHeaderHeight = 0;
    _tableView.estimatedSectionFooterHeight = 0;
    
    UIButton *logoutBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:logoutBtn];
    [logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    logoutBtn.frame = CGRectMake(20, self.tableView.y+self.tableView.height+10, SCREEN_WIDTH-40, [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(14)].height+20);
    logoutBtn.backgroundColor = UIMainColorRGB;
    [logoutBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [logoutBtn addTarget:self action:@selector(logoutAction:) forControlEvents:UIControlEventTouchUpInside];
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (self.cell == nil) {
        self.cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    }
    
    NSArray *arr = self.infoArr[indexPath.section];
    
    self.cell.textLabel.text = arr[indexPath.row];
    
    self.cell.textLabel.font = kUHSystemFontWithSize(14);
    self.cell.textLabel.textColor = [UIColor grayColor];
    self.cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    if ([self.cell.textLabel.text isEqualToString:@"清理缓存"]) {
        UILabel *cache = [[UILabel alloc] initWithFrame:CGRectMake(SW(2), 10, SW(2)-SW(20), [LZCTools textSizeWithText:self.cell.textLabel.text font:self.cell.textLabel.font].height)];
        [self.cell addSubview:cache];
        cache.textColor = [UIColor grayColor];
        cache.textAlignment = NSTextAlignmentRight;
        cache.font = kUHSystemFontWithSize(14);
        cache.text = [NSString stringWithFormat:@"%.2fM", [self filePath]];
        self.cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    _cell.preservesSuperviewLayoutMargins = NO;
    _cell.separatorInset = UIEdgeInsetsZero;
    _cell.layoutMargins = UIEdgeInsetsZero;
    
    return self.cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.infoArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSArray *arr = self.infoArr[section];
    return arr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [LZCTools textSizeWithText:self.cell.textLabel.text font:self.cell.textLabel.font].height+20;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section < self.infoArr.count-1) {
        return 10;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.section);
    BindingPhoneViewController *phoneVC = [[BindingPhoneViewController alloc] init];
    phoneVC.phone = GetUserDefaule(USERINFO)[@"mobile"];
    switch (indexPath.section) {
        case 0:
        {
            switch (indexPath.row) {
                case 0:
                {
                    
                    [self.navigationController pushViewController:phoneVC animated:YES];
                }
                    break;
                case 1:
                {
                    NSLog(@"修改密码被点击");
                    [self.navigationController pushViewController:[[ChangePassWordViewController alloc] init] animated:YES];
                }
                    break;
                default:
                    break;
            }
            
        }
            break;
        case 1:
        {
            switch (indexPath.row) {
                case 0:
                {
                    NSLog(@"清理缓存被点击");
                    if ([self filePath] > 0.009999) {
                        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                        [self clearFile];
                    }
                }
                    break;
                case 1:
                {
//                    NSLog(@"帮助被点击");
//                }
////                    break;
//                case 2:
//                {
                    NSLog(@"关于平台被点击");
//                    [self.navigationController pushViewController:[[PerMessageDetailsViewController alloc] init] animated:YES];
                    [self.navigationController pushViewController:[[PlatformIntroViewController alloc] init] animated:YES];
                }
                    break;
                case 2:
                {
                    NSLog(@"联系客服被点击");
                    NSMutableString *tstr = [[NSMutableString alloc] initWithFormat:@"tel:17825838589"];
                    NSLog(@"手机号======%@",tstr);
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tstr] options:@{} completionHandler:nil];
                }
                    break;
                case 3:
                {
                    NSLog(@"反馈意见被点击");
                    [self.navigationController pushViewController:[[FeedbackViewController alloc] init] animated:YES];
                }
                    break;
                default:
                    break;
            }
        }
            break;
        default:
            break;
        }
}

#pragma mark ==========响应方法==========
// 显示缓存大小
- (float)filePath {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return [self folderSizeAtPath:cachePath];
}
//1:首先我们计算一下 单个文件的大小
- (long long)fileSizeAtPath:(NSString *)filePath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
//2:遍历文件夹获得文件夹大小，返回多少 M（提示：你可以在工程界设置（)m）
- (float)folderSizeAtPath:(NSString *)folderPath {
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) {
        return 0;
    }
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil) {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
// 清理缓存
- (void)clearFile {
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachePath];
    NSLog(@"cachePath = %@", cachePath);
    for (NSString *p in files) {
        NSError *error = nil;
        NSString *path = [cachePath stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
            [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
        }
    }
    [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
}
- (void)clearCacheSuccess {
    NSLog(@"清理缓存成功");
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:1];//刷新
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:index,nil] withRowAnimation:UITableViewRowAnimationNone];
}

/**
 退出登录
 */
- (void)logoutAction:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"是否退出登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"不" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
		
		[[HUDHelper sharedInstance] syncLoading:@"正在退出"];
		[[IMAPlatform sharedInstance] logout:^{
			[[HUDHelper sharedInstance] syncStopLoadingMessage:@"退出成功" delay:1.0 completion:^{
				AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
				LoginViewController *loginVC = [[LoginViewController alloc] init];
				loginVC.isLogut = YES;
				UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
				appDelegate.window.rootViewController = nav;
				RemoveUserDefaule(USERINFO);
				[APPServer refreshToken];
			}];
			
		} fail:^(int code, NSString *err) {
			[[HUDHelper sharedInstance] syncStopLoadingMessage:IMALocalizedError(code, err) delay:1.0 completion:^{
				AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
				LoginViewController *loginVC = [[LoginViewController alloc] init];
				loginVC.isLogut = YES;
				UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loginVC];
				appDelegate.window.rootViewController = nav;
				RemoveUserDefaule(USERINFO);
				[APPServer refreshToken];
			}];
		}];
        
    }]];
    [self presentViewController:alert animated:YES completion:nil];

}

/**
 检查网络
 */
- (void)checkNetwork {
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"没有网络(断网)");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"手机自带网络");
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WIFI");
                break;
        }
    }];
    // 3.开始监控
    [manager startMonitoring];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
